

#include "app_net.h"

#include "../../inc/pt_app.h"

static pthread_t	tcp_server_thread;

static server_para_t tcp_p;

int32_t app_tcp_server_task(void *para)
{
    int n   = 0;
    int len = 0;
	int ret = -1;
    struct sockaddr_in server, client;

    // socket create and verification
    tcp_p.s_sockfd = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
    if(tcp_p.s_sockfd == -1) {
        log_e("socket create failed...\n");
        return -1;
    }

    log_n("socket successfully created..\n");
    memset(&server,0,sizeof(struct sockaddr_in));

    // assign IP, PORT
    server.sin_family      = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port        = htons(CFG_LISTEN_PORT);

	ret = bind(tcp_p.s_sockfd,(struct sockaddr*)&server,sizeof(server));
	if(ret != 0){
        log_e("socket bind failed %d...\n",ret);
        return -1;
	}

	log_n("socket bind successfully...\n");

	ret = listen(tcp_p.s_sockfd,5);
	if(ret != 0){
        log_e("socket listen failed...\n");
        return -1;
	}
	
	log_d("socket listen successfully...\n");
	//***************************************************************

	while(1)
	{
		usleep(1000);
		//***************************************************************

		len = sizeof(client);
		tcp_p.s_connfd = accept(tcp_p.s_sockfd, (struct sockaddr*)&client, &len);
		if(tcp_p.s_connfd < 0){
			continue;
		}
		
		log_d("socket accept successfully...\n");
		//***************************************************************

		while(1)
		{

			usleep(1000);
			//***************************************************************
			memset(tcp_p.s_r_buff,0,sizeof(tcp_p.s_r_buff));
			ret = recv(tcp_p.s_connfd, tcp_p.s_r_buff, sizeof(tcp_p.s_r_buff),0);
			if(ret <= 0){
				break;
			}
			
			log_n("recv:%s\n",tcp_p.s_r_buff);
			//***************************************************************
			if(!strcmp(tcp_p.s_r_buff,"right"))
			{
				message_packet_send(MSG_KEY_RIGHT,0,0);
			}	
			else if(!strcmp(tcp_p.s_r_buff,"left"))
			{
				message_packet_send(MSG_KEY_LEFT,0,0);
			}
			//***************************************************************
			memset(tcp_p.s_w_buff,0,sizeof(tcp_p.s_w_buff));

			sprintf(tcp_p.s_w_buff,"%s%s","rk3568:",tcp_p.s_r_buff);
			
			ret = send(tcp_p.s_connfd, tcp_p.s_w_buff, strlen(tcp_p.s_w_buff),0);
			if(ret != strlen(tcp_p.s_w_buff)){
				log_e("socket send error\n");
			}
			//***************************************************************

		}
	}
}


int app_server_create(void)
{

	int ret = -1;
	
	ret=pthread_create(&tcp_server_thread, NULL, app_tcp_server_task, NULL);
	if(ret != 0){
		log_e("error=%s\n",strerror(ret));
	}

	return 0;
}


